package com.ht.api.handler;

import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import com.ht.api.bean.AjaxResult;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.exception.HtSqlException;

import lombok.extern.slf4j.Slf4j;

/**
 * 通用错误处理器
 * @author asq
 * @createTime 2024年11月28日 16:05:33
 */
@ControllerAdvice
@Slf4j
public class ErrorHandler {

	@ExceptionHandler(value = HtException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ResponseBody
	public AjaxResult errorResponse(HtException exception) {
		return AjaxResult.error(cn.hutool.http.HttpStatus.HTTP_BAD_REQUEST, exception.getMessage());
	}
	
	@ExceptionHandler(value = HtSqlException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ResponseBody
	public AjaxResult errorResponse(HtSqlException exception) {
		log.error("SQL执行失败，请检查参数~", exception);
		return AjaxResult.error(cn.hutool.http.HttpStatus.HTTP_BAD_REQUEST, "SQL执行失败，请检查参数~");
	}
	
	@ExceptionHandler(value = HttpMessageNotReadableException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ResponseBody
	public AjaxResult errorResponse(HttpMessageNotReadableException exception) {
		return AjaxResult.error(cn.hutool.http.HttpStatus.HTTP_BAD_REQUEST, "json参数格式错误~");
	}
	
	@ExceptionHandler(value = NoResourceFoundException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ResponseBody
	public AjaxResult errorResponse(NoResourceFoundException exception) {
		return AjaxResult.error(cn.hutool.http.HttpStatus.HTTP_BAD_REQUEST, "接口路径错误~");
	}
	
	@ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ResponseBody
	public AjaxResult errorResponse(HttpMediaTypeNotSupportedException exception) {
		return AjaxResult.error(cn.hutool.http.HttpStatus.HTTP_BAD_REQUEST, "需要在body中传递json参数~");
	}
	
	@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ResponseBody
	public AjaxResult errorResponse(HttpRequestMethodNotSupportedException exception) {
		return AjaxResult.error(cn.hutool.http.HttpStatus.HTTP_BAD_REQUEST, "请使用POST方式访问接口~");
	}

	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public AjaxResult errorResponse(Exception exception) {
		log.error("后台出错了！", exception);
		return AjaxResult.error("服务器发生异常~");
	}

}